package com.ganbo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * Created by ganbo on 2019/6/24.
 */
@Service
public class JedisService {

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 获取锁
     */
    public boolean tryLock(String lockKey) {
        return redisTemplate.opsForValue().setIfAbsent(lockKey, String.valueOf(System.currentTimeMillis()));
    }

    /**
     * 获取锁
     *
     * @param lockKey
     * @param time    超时释放时间(单位秒)
     * @return
     */
    public boolean tryLock(String lockKey, long time) {
        return redisTemplate.opsForValue().setIfAbsent(lockKey, String.valueOf(System.currentTimeMillis()), time, TimeUnit.SECONDS);
    }


    /**
     * 释放锁
     */
    public boolean removeLock(String lockKey) {
        redisTemplate.delete(lockKey);
        return true;
    }
}
